package com.choudou5.solr.web.handler.sys;

import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.bean.DicExtWords;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SqlQueryBean;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.service.DicExtWordsService;
import com.choudou5.solr.service.ServiceHelper;
import com.choudou5.solr.utils.SqlQueryBuilder;
import com.choudou5.solr.utils.UploadUtil;
import com.choudou5.solr.web.handler.BaseHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Name：扩展词库 处理器
 * @Author：choudou5
 * @Date：2018-07-15
 */
public class DicExtWordsHandler extends BaseHandler {

    private final DicExtWordsService dicExtWordsService = ServiceHelper.singleton(DicExtWordsService.class);

    @Override
    public void execute(String method, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("DicExtWordsHandler method:{}", method);
        switch (method){
            case "pageList":
                pageList(req, resp);
                break;
            case "add":
                add(req, resp);
                break;
            case "importWords":
                importWords(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }


    /**
     * 分页列表
     * @param req
     * @param resp
     */
    private void pageList(HttpServletRequest req, HttpServletResponse resp){
        SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
        sqlQueryBean.setOrderDefParam("create_time", "desc");
        PageResult<DicExtWords> pageResult = dicExtWordsService.findPage(sqlQueryBean);
        req.setAttribute("pageResult", pageResult);
        PageJumpUtil.forward("dicExtWords", req, resp);
    }

    @ReqMapping(desc = "新增扩展词", method = ReqMethod.POST)
    private void add(HttpServletRequest req, HttpServletResponse resp){
        String keyword = RequestUtil.getStrParameter(req, "keyword");
        boolean valid = validParam(req, resp, keyword, "关键词");
        if(valid){
            dicExtWordsService.add(keyword);
            PageJumpUtil.writeJsonOk("添加成功", resp);
        }
    }

    @ReqMapping(desc = "导入词库", method = ReqMethod.POST)
    private void importWords(HttpServletRequest req, HttpServletResponse resp){
        List<String> lines = UploadUtil.readUploadFileLines(req);
        dicExtWordsService.imporWords(lines);
        PageJumpUtil.writeJsonOk("导入完成", resp);
    }

}
